package cn.gzjp.modules.dt.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.dt.entity.Question;
import cn.gzjp.modules.dt.service.QuestionService;

/**
 * 题目Controller
 * @author zengcp
 * @version 2018-02-24
 */
@Controller
@RequestMapping(value = "${adminPath}/dt/question")
public class QuestionController extends BaseController {

	@Autowired
	private QuestionService questionService;
	
	
	/**
	 * 题目列表页面
	 */
	@RequestMapping(value = {"list", ""})
	public String list(Question question, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Question> page = questionService.findPage(new Page<Question>(request, response), question); 
		model.addAttribute("page", page);
		return "modules/dt/questionList";
	}

	/**
	 * 查看，增加，编辑题目表单页面
	 */
	@RequestMapping(value = "form")
	public String form(Question question, Model model) {
		question = questionService.get(question.getQuestionId());
		model.addAttribute("question", question);
		return "modules/dt/questionForm";
	}

	/**
	 * 保存题目
	 */
	@RequestMapping(value = "save")
	public String save(Question question, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, question)){
			return form(question, model);
		}
		if(!question.getIsNewRecord()){//编辑表单保存
			Question t = questionService.get(question.getQuestionId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(question, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			questionService.save(t);//保存
		}else{//新增表单保存
			questionService.save(question);//保存
		}
		addMessage(redirectAttributes, "保存题目成功");
		return redirect("/dt/question/?repage");
	}
	
	/**
	 * 删除题目
	 */
	@RequestMapping(value = "delete")
	public String delete(Question question, RedirectAttributes redirectAttributes) {
		questionService.delete(question);
		addMessage(redirectAttributes, "删除题目成功");
		return redirect("/dt/question/?repage");
	}
	
	/**
	 * 批量删除题目
	 */
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			questionService.delete(questionService.get(id));
		}
		addMessage(redirectAttributes, "删除题目成功");
		return redirect("/dt/question/?repage");
	}
	
	/**
	 * 导出excel文件
	 */
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Question question, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "题目"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Question> page = questionService.findPage(new Page<Question>(request, response, -1), question);
    		new ExportExcel("题目", Question.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出题目记录失败！失败信息："+e.getMessage());
		}
		return redirect("/dt/question/?repage");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("dt:question:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Question> list = ei.getDataList(Question.class);
			for (Question question : list){
				try{
					questionService.save(question);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条题目记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条题目记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入题目失败！失败信息："+e.getMessage());
		}
		return redirect("/dt/question/?repage");
    }
	
	/**
	 * 下载导入题目数据模板
	 */
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "题目数据导入模板.xlsx";
    		List<Question> list = Lists.newArrayList(); 
    		new ExportExcel("题目数据", Question.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/dt/question/?repage");
    }
	@ModelAttribute
	public Question get(@RequestParam(required=false) String id) {
		Question entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = questionService.get(id);
		}
		if (entity == null){
			entity = new Question();
		}
		return entity;
	}
	

}